<?php

namespace App\Exceptions;

use App\Consts\ExceptionCode;
use Doctrine\DBAL\Query\QueryException;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;

class Handler extends ExceptionHandler
{

    /**
     * A list of the exception types that are not reported.
     *
     * @var array
     */
    protected $dontReport = [
        //
    ];

    /**
     * A list of the inputs that are never flashed for validation exceptions.
     *
     * @var array
     */
    protected $dontFlash = [
        'password',
        'password_confirmation',
    ];

    /**
     * Register the exception handling callbacks for the application.
     *
     * @return void
     */
    public function register()
    {
        $this->reportable(function (\Exception $e) {
            if (app()->bound('sentry') && $this->shouldReport($e)) {
                app('sentry')->captureException($e);
            }
        });
    }

    /**
     * Render an exception into an HTTP response.
     *
     * @param \Illuminate\Http\Request $request
     * @param \Exception $exception
     * @return \Illuminate\Http\JsonResponse|\Symfony\Component\HttpFoundation\Response
     * @throws \Throwable
     */
    public function render($request, $exception)
    {
        $code = 0;
        if ($exception instanceof \HttpException) {
            $code = ExceptionCode::HANDLER_ERROR;
        }
        if ($exception instanceof QueryException) {
            $code = ExceptionCode::HANDLER_SQL;
        }
        if ($exception instanceof \ReflectionException) {
            $code = ExceptionCode::HANDLER_CRITICAL;
        }
        if ($exception instanceof \RuntimeException) {
            $code = ExceptionCode::HANDLER_ALTER;
        }
        if ($exception instanceof \ErrorException) {
            $code = ExceptionCode::HANDLER_EMERGENCY;
        }
        if ($exception instanceof \ParseError) {
            $code = ExceptionCode::HANDLER_PARSE;
        }
        if($code){
            $result = [
                'errMsg' => "[".ExceptionCode::HANDLER_LEVELS[$code]['desc']."] - " . $exception->getMessage(),
                'errCode' => $code,
                'file' => $exception->getFile() . ' : ' . $exception->getLine(),
                'request' =>$request->input(),
            ];
            // send sentry log
            sendSentry($exception);
            return Error::handle('', ExceptionCode::CODE_FAIL, $result);
        }
        return parent::render($request, $exception);
    }

}
